﻿using System.Web.Mvc;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using System.Drawing;
using System;

namespace Weibo4SharpWeb.Controllers
{
    public class HomeController : WeiboControllerBase
    {
        //
        // GET: /Home/{Index}/{id = 1}

        public ActionResult Index(int id = 1)
        {
            var weibos = GetAuthenticatedService().ListWeibosOnFriendsTimeline(id, 20);

            weibos = GetAuthenticatedService().ListWeiboCountsBindToWeibos(weibos);

            ViewBag.PageId = id;
            ViewBag.HasPrev = id > 1;
            ViewBag.HasNext = weibos.Count() == 20;

            if (Request.IsAjaxRequest())
            {
                return PartialView("StatusList", weibos);
            }

            return View(weibos);
        }

        [HttpPost]
        public ActionResult Update(string status)
        {
            var file = Request.Files["pic"];

            if (string.IsNullOrEmpty(status))
            {
                status = "Share";
            }

            if (file != null && file.ContentLength > 0)
            {
                var di = new DirectoryInfo(Server.MapPath("\\upload"));

                if(!di.Exists)
                {
                    di.Create();
                }

                var filename = di.FullName + "\\" + DateTime.Now.ToFileTimeUtc() + file.FileName.Substring(file.FileName.LastIndexOf("."));

                file.SaveAs(filename);

                var weibo = GetAuthenticatedService().SendWeiboWithPic(status, filename);

            }
            else
            {
                var weibo = GetAuthenticatedService().SendWeibo(status);
            }

            return new RedirectResult("/");
        }

        public ActionResult About()
        {
            return View();
        }

        public ActionResult Contact()
        {
            return View();
        }
    }
}
